package com.pb.metadata.controller;

import com.pb.infra.auth.entity.byd.Index;
import com.pb.infra.auth.mapper.CommonMapper;
import com.pb.infra.auth.service.CommonService;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.util.Constant;
import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.infra.oth.util.StringUtil;
import com.pb.infra.oth.util.SysLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 田起立
 * @date 2023/10/25
 */
@Slf4j
@RestController
@RequestMapping("v1/metadata/dataEntry")
public class DataEntryController {


    @Autowired
    private CommonService commonService;
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private JwtTokenConfig jwtTokenConfig;

    @PostMapping("insert")
    @SysLog(tableName = "利润预测数据录入", action = Constant.ACTION_NAME.ADD, menuName = "利润预测数据录入")
    public Result insert(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        List<Map<String, Object>> list = (List<Map<String, Object>>) params.get("list");
        Map<String, Object>  form = (Map<String, Object>) params.get("form");
        List<Index> indices = commonMapper.selectIndex();
        ArrayList<Map<String, Object>> fixedList = new ArrayList<>();
        ArrayList<Map<String, Object>> indexList = new ArrayList<>();
        int version = commonMapper.getMaxVersion();
        for (Map<String, Object> map : list) {
            for (Index index : indices) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    HashMap<String, Object> indexMap = new HashMap<>();
                    if (entry.getKey().equals(index.getProp())) {
                        indexMap.put("value", entry.getValue());
                        String prdtName = map.get("prdtName").toString();
                        String dateDt = map.get("dateDt").toString();
                        indexMap.put("rptName", index.getRptIndName());
                        indexMap.put("rptIndId", index.getRptIndId());
                        indexMap.put("prdtName", prdtName);
                        indexMap.put("dateDt", dateDt.replace("-",""));
                        indexMap.put("forecastBT", form.get("startTime"));
                        indexMap.put("forecastET", form.get("endTime"));
                        indexMap.put("version",version);
                        indexList.add(indexMap);
                    }
                }
            }
        }
        for (Map<String, Object> map : indexList) {
            commonService.insertIndexData(map);
        }

        return Result.ok(null);
    }

    @PostMapping("selectIndexData")
    public Result selectIndex(@RequestBody Map<String, Object> paramMap){
        //返回的处理数据
        ArrayList<Map<String,Object>> returnList = new ArrayList<>();



        //39个指标字段名
        List<Index> indices = commonMapper.selectIndex();

        Map<String, Object>  form = (Map<String, Object>) paramMap.get("form");
        // 开始日期
        String startTime = form.get("startTime").toString().replace("-","");
        // 结束日期
        String endTime = form.get("endTime").toString().replace("-","");
        // 获取中间所有的日期
        YearMonth startYearMonth = YearMonth.parse(startTime, DateTimeFormatter.ofPattern("yyyyMM"));
        YearMonth endYearMonth = YearMonth.parse(endTime, DateTimeFormatter.ofPattern("yyyyMM"));
        //开始月份到结束月份的集合,格式202301
        List<String> dateList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        while (!startYearMonth.isAfter(endYearMonth)) {
            dateList.add(startYearMonth.format(formatter));
            startYearMonth = startYearMonth.plusMonths(1);
        }
        //车型集合
        List<Map<String,Object>> tempData= (List<Map<String,Object>>) form.get("selectedNodes");
        List<String> carList= tempData.stream().map(it ->it.get("label").toString()).collect(Collectors.toList());
        for (int i = 0; i < dateList.size(); i++) {
            //第i个日期
            String s = dateList.get(i).toString();
            //算i月的每款车型的
            for (int  j= 0; j < carList.size(); j++) {
                //存一条数据
                Map<String,Object> map = new HashMap<>();
                //第j个车型
                String b = carList.get(j).toString();
                // 查询参数
                Map<String, Object> param = new HashMap<>();
                param.put("dataDt",s);
                param.put("propId",b);
                //根据日期车型去查出39个指标数据
                List<Map<String,Object>> list = commonMapper.selectDataByVersion(param);
                //把39个指标数据变成一条数据
                map.put("dateDt",s);
                map.put("prdtName",b);
                for (int  k= 0; k < list.size(); k++) {
                    if(!list.get(k).get("indicator_value").toString().equals("0.00")) {
                        map.put(indices.get(k).getProp() , list.get(k).get("indicator_value"));
                    }
                }
                returnList.add(map);

            }
//            List<Index> indices = commonService.selectIndex();
        }

        return Result.ok(returnList);
    }
    @PostMapping("/exportExcel")
    @SysLog(tableName = "利润预测数据录入", action = Constant.ACTION_NAME.EXP, menuName = "利润预测数据录入")
    public Map<String, Object> exportColumnExcel(@RequestBody Map<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        List<Index> indices = commonMapper.selectIndex();
        List<Map<String,Object>> list = (List<Map<String, Object>>) paramMap.get("list");
        List<String> strList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        List<String> dateTypeList = new ArrayList<>();
        List<String> commentList = new ArrayList<>();

        strList.add("预测月份");
        strList.add("款项");
        nameList.add("dateDt");
        nameList.add("prdtName");
        dateTypeList.add("STRING");
        dateTypeList.add("STRING");
        for (Index index : indices) {

            strList.add(index.getRptIndName());
            nameList.add(index.getProp());
            dateTypeList.add("STRING");
        }
        String[] tmpStr = strList.toArray(new String[0]);
        String[] tmpName = nameList.toArray(new String[0]);
        String[] tmpDataType = dateTypeList.toArray(new String[0]);
        String[][] strArr = {{}};
        String[][] nameArr = {{}};
        String[][] dataType = {{}};
        String[][] comments = {{"","","","","","",""}};
        strArr[0] = tmpStr;
        nameArr[0] = tmpName;
        dataType[0] = tmpDataType;
        Object[] obj = {list};
        String[] jobBookName = {"利润预测数据录入"};
        paramMap.put("jobBookName", jobBookName);
        paramMap.put("title", strArr);
        paramMap.put("order", nameArr);
        paramMap.put("comments", comments);
        paramMap.put("token", token);
        paramMap.put("data", obj);
        paramMap.put("dataType", dataType);
        paramMap.put("fileName", "利润预测数据录入");
        return paramMap;
    }
}
